import{getCartsGoods,changgoodsnum,deletegood,deletegoodall,pldelete} from '@/api/index.js'
import Vue from 'vue'

const state={
  cartgoods:{},//购物车商品信息

}
const actions={
  //请求购物车
  async cartlist({commit},params){
    let result=await getCartsGoods(params)
 if(result.data.code==200){
  commit("CART_GOODS_LIST", {cartgoods: result.data.msg})
 }
   
  },
  //更改购物车单个的数量
   async updatanum({commit},{goods, num, user_id}){
      let result= await changgoodsnum(goods, num, user_id)
      if(result.data.code==200){
        commit("cartnum", {goods,num})
      }
      

   },
   //单个商品的选中
   ischeck({commit},{goods}){
    commit("ischen",{goods})
   },
   //全选
   selectedall({commit},{ischecked}){
    commit("ISCHECKED",{ischecked})
   },
   //删除单个商品
  async deletegoods({commit},{goods,user_id}){
let result=await deletegood(goods,user_id)
if(result.data.code==200){
  commit("DELETEGOODS",{goods})
}
   },
   //删除全部商品
  async deleteall({commit},{user_id}){
    const result=await deletegoodall(user_id)
    if(result.data.code==200){
      commit("DELETEALL")
    }

   },
   //批量删除
   async pldeleteCart({commit},{id,a}){
    let result= await pldelete(id,a)
    if(result.data.code==200){
      commit("pldee",{a})
    }
   
   }


}
const mutations={
  CART_GOODS_LIST(state,{cartgoods}){
    state.cartgoods=cartgoods
  },
  cartnum(state,{goods,num}){
    const index=state.cartgoods.indexOf(goods)
    state.cartgoods[index].buy_count=num
  
  },
  ischen(state,{goods}){
    const index=state.cartgoods.indexOf(goods)
    if(!goods.checked){
      state.cartgoods[index].checked=true
      
    }else{
      state.cartgoods[index].checked=!state.cartgoods[index].checked
    }

  },
  ISCHECKED(state,{ischecked}){
    state.cartgoods.forEach((item)=>{
      if(item.checked){
        item.checked= !ischecked
      }else{
        //全局设置checked
        Vue.set(item,'checked',!ischecked)
      }

  })
},    
    DELETEGOODS(state,{goods}){
      goods.buy_count=0;
      const index=state.cartgoods.indexOf(goods)
state.cartgoods.splice(index,1)
    },
    pldee(state,{a}){
      for(let i=0;i<a.length;i++){
        if(state.cartgoods.indexOf(a[i])!=-1){
          const index=state.cartgoods.indexOf(a[i])
          state.cartgoods.splice(index,1)

        }
       

      }

    },
    
}

export default{
  namespaced: true,//命名空间
  actions,
  mutations,
  state
}